﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

public class udp{

    private Socket _sock;
    Thread _threadReceive;
    public void CreateUdp(int listenPort)
    {
        _sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
        ProtocolType.Udp);
        _sock.SetSocketOption(SocketOptionLevel.Socket,
        SocketOptionName.Broadcast, 1);
        StartListen(listenPort);
    }

    private void StartListen(int comPort)//未完善，注意防止同时调用多次创建
    {
        IPEndPoint iep =new IPEndPoint(IPAddress.Any, comPort);
        _sock.Bind(iep);

        _threadReceive = new Thread(new ThreadStart(ReciveMsg));
        _threadReceive.IsBackground = true;
        _threadReceive.Start(); 
    }

    private void ReciveMsg()
    {
        byte[] data = new byte[1024];
        while (true)
        {
            int recv = _sock.Receive(data);
            if (recv>0)
            {
                data = data.Take(recv).ToArray();
                TransMsg msg = SocketTool.TransByte2Msg(data);
                Debug.Log(msg._msgData);
            }
        }    
    }

    public void BroadcastMessage(string msgType,string msg,int comPort)
    {
        byte[] buffer = SocketTool.TransMsg2Byte(msgType, msg);
        _sock.SendTo(buffer, new IPEndPoint(IPAddress.Broadcast,comPort));
    }

    private void SingleCastMessage(string msgType, string msg,string ip,int comPort)
    {
        byte[] buffer = SocketTool.TransMsg2Byte(msgType, msg);
        _sock.SendTo(buffer, new IPEndPoint(IPAddress.Parse(ip), comPort));
    }

}
